<template>
  <div class="quality_agent" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="timeQuery" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski ski1">{{$t('public.agent')}} :</span>
                  <!-- <el-select v-model="timeQuery.user"
                              multiple
                              filterable
                              size="mini"
                              :placeholder="$t('report.pleChoseAgent')">
                      <el-option
                        v-for="item in agentOptions"
                        :label="item.label"
                        :value="item.value"
                        :key="item.value">
                      </el-option>
                    </el-select> -->
                  <m7Select class="el-select" filterable multiple :options="selectAgents" v-model="timeQuery.user"></m7Select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id = "id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.quaQualityAll')}}<br/>
                {{$t('report.quaQualityCallNum')}}<br/>
                {{$t('report.quaQualitySessionNum')}}<br/>
                {{$t('report.quaPropleQualityNum')}}<br/>
                {{$t('report.quaInterCheckNum')}}<br/>
                {{$t('report.quaAppealsSucNum')}}<br/>
                {{$t('report.quaWrongRate')}}<br/>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :config="headOptions"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, colorConfigArr, checkTime } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'quality_agent',
    data () {
      return {
        selectedAgentList: [],
        agentOptions: [],
        isFold: false,
        loading: false,
        id: 'autoqc_agent_workload_report',
        title: this.$t('report.qualityReportAgent'),
        platform: '',
        timeQuery: {
          user: []
        },
        dialogVisible: false,
        serverData: [],
        headOptions: [],
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.qualityReportAgent') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agentOptions
      },
      tableData () {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }
        let data = deepClone(this.serverData)
        return data
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'agentName' || item.name === 'errorRate') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(datas[i].agentName)
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      isShowFold (bool) {
        this.isFold = bool
      },
      searchOrExport (isExport) {
        let data = {
          account: this.$store.state.session.user.account,
          query: { reportType: this.id, accountId: this.$store.state.session.user.account }
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.query = Object.assign({}, data.query, query)
        this.loading = true
        this.$store.dispatch('queryQcAgentWorkloadReport', data).then((res) => {
          // 表头
          this.loading = false

          for (var i = 0; i < res.data.length; i++) {
            res.data[i].errorRate += '%'
            let agent = this.$store.getters.agents[res.data[i].agentId]
            res.data[i].agentName = agent ? agent.displayName + '(' + agent.exten + ')' : ''

            if (isExport) {
              res.data[i].agentName = agent ? agent.displayName : ''
              res.data[i].agentExten = agent ? agent.exten : ''
            }
          }
          if (isExport) {
            var serverData = deepClone(res.data)

            if (!serverData || serverData.length === 0) {
              serverData = []
            }

            var headOptions = deepClone(res.tableHeader.Config) || []

            var ConfigsTemp = []
            headOptions.forEach(config => {
              ConfigsTemp.push(config)
              if (config.name === 'agentName') {
                ConfigsTemp.push({
                  show: config.show,
                  displayname: '工号',
                  name: 'agentExten'
                })
              }
            })

            var headers = headOptionsToXlsxHeaders(ConfigsTemp)

            var dh = XlsxUtil.getDownloadHelper(headers, serverData)
            var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
            dh.download(this.$t('report.qualityReportAgent') + timeStamp)
          } else {
            this.serverData = deepClone(res.data)
            this.headOptions = deepClone(res.tableHeader.Config)
          }
        })
      },
      search () {
        this.searchOrExport()
      },
      exportXlsx () {
        this.searchOrExport(true)
      },
      exportXls () {
        let data = {
          Method: 'exportAutoqcAgentWorkloadReportExcel',
          Query: {reportType: this.id, accountId: this.$store.state.session.user.account}
        }
        let query = deepClone(this.timeQuery)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportRobotMessageExcel', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.qualityReportAgent') + searchTime(this.timeQuery), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .quality_agent
    .m7-select
      width 200px
    .export
      .pdf
        margin 0px
    .search
      .ski1
        margin-right 24px
</style>
